package com.csoa.community.requests;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.chinaface.JSONArray;
import org.json.chinaface.JSONObject;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.csoa.community.activity.BaseActivity.OnUICallback;
import com.csoa.community.bean.RiChengModel;
import com.csoa.community.net.ErrorMsg;
import com.csoa.community.net.WcfAsyncTask;
import com.csoa.community.singletons.GlobalVars;
import com.csoa.community.utils.AndroidUtils;
import com.csoa.community.utils.StringUtils;

public class RiChengRequest extends AbstractRequest {

	public List<RiChengModel> data;
	
	Context cxt;
	
	public RiChengRequest(List<BasicNameValuePair> requestValues, Context cxt) {
		super(method_richeng_list, requestValues);
		this.cxt = cxt;
	}

	@Override
	protected void parseRemaingInfo(String json) throws ErrorMsg, JSONException {
		
		if(!StringUtils.isEmpty(json)) {
			
			if (data == null) {
				data = new ArrayList<RiChengModel>();
			}
			
			data.clear();
			
			try {
				JSONArray ja = new JSONArray(json);
				RiChengModel model;
				JSONObject jb;
				for (int i = 0; i < ja.length(); i++) {
					model = new RiChengModel();
					jb = ja.getJSONObject(i);
					Log.e("", jb.toString());
					model.id = jb.getString("event_id");
					model.name = jb.getString("text");
//					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//					String time = sdf.format(new Date(System.currentTimeMillis() + (1000 * 5)));
//					model.time_start = time;
					model.time_start = jb.getString("Start_date");
					model.time_end = jb.getString("End_date");
					data.add(model);
				}
				setAlerm(data, cxt);
			} catch (org.json.chinaface.JSONException e) {
				e.printStackTrace();
			}
		}
		
	}
	
//	private final static String cache_file_name_richeng = "cache_file_name_richeng";
	private final static String cache_file = "cache_file_richeng";
	private final static String cache_tixing_jiange_time = "cache_tixing_jiange_time";
	
	public static int getTiXingJianGe(Context cxt) {
		String str = AndroidUtils.getGlobal(cache_file, cache_tixing_jiange_time, cxt);
		if (StringUtils.isEmpty(str)) {
			setTiXingJianGe(cxt, 2);
			return 2;
		} else {
			return Integer.parseInt(str);
		}
	}
	
	public static void setTiXingJianGe(Context cxt, int type) {
		AndroidUtils.setGlobal(cache_file, cache_tixing_jiange_time, type + "", cxt);
	}
	
	public static void tryInitAlerm(final Context cxt) {
		if (GlobalVars.currentUser == null) {
			return;
		}
		Log.e("", "正在尝试重新设定闹铃");
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("LogName", GlobalVars.currentUser.loginName));
		params.add(new BasicNameValuePair("PageSize", 30 + ""));
		params.add(new BasicNameValuePair("CurrPage", 1 + ""));
		new WcfAsyncTask(cxt, new OnUICallback() {
			@Override
			public void onGetResult(AbstractRequest request) {
			}

			@Override
			public void onCancel() {
			}

			@Override
			public void onProgress(int progress, String msg) {
			}
		}).execute(new RiChengRequest(params, cxt));
	}
	
	private static void setAlerm(final List<RiChengModel> data, final Context cxt) {
		Log.e("", "正在重新设定闹铃");
		if (data == null || data.size() <= 0) {
			return;
		}
		clearAlerm(cxt);
		long t = getTiXingJianGeLong(cxt);
		if(t <= 0) {
			return;
		}
		for (int i=0; i<data.size(); i++) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
//				long time = (sdf.parse(data.get(i).time_start)).getTime();
				long time = (sdf.parse(data.get(i).time_start)).getTime() - t;
				Log.e("", "time:" + time + " sys:" + System.currentTimeMillis());
				if (time <= System.currentTimeMillis()) {
					Log.e("", "这个会议已经过时");
				} else {
					setAlarmTime(cxt, time, data.get(i));
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		Log.e("", "重新设定闹铃完成");
	}
	
	public static final String action = "com.csoa.action.alerm";
	public static final String extra_model = "extra_model";
	
	private static int i = 0;
	
	private static void setAlarmTime(Context context,  long timeInMillis, RiChengModel model) {
		AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(action);
		intent.putExtra(extra_model, model);
		PendingIntent sender = PendingIntent.getBroadcast(
		        context, i, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		am.set(AlarmManager.RTC_WAKEUP, timeInMillis, sender);
		i ++;
	 }
	private static void clearAlerm(Context context) {
		AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(action);
		PendingIntent sender = PendingIntent.getBroadcast(
				context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		am.cancel(sender);
	}
	
	public static long getTiXingJianGeLong(Context cxt) {
		
		switch (getTiXingJianGe(cxt)) {
		case 0:
			return 1000 * 60 * 30;
		case 1:
			return 1000 * 60 * 60;
		case 3:
			return 0;
		case 2:
		default:
			return 1000 * 60 * 60 * 24;
		}
	}
	
}
